﻿Imports PdfSharpCore.Drawing
Imports PdfSharpCore.Pdf
Imports PdfSharpCore.Pdf.IO
Imports Microsoft.Office.Interop.Excel
Imports System.IO
Module fun
    Public Sub InsertImages()
        ' 选择 PDF 文件
        Dim pdfPath As String = "" '= "E:\Project\VSTO\ImpPicIntoPdf\1.pdf"
        Dim imagePath As String '= "E:\Project\VSTO\ImpPicIntoPdf\WC2001267.png"

        If SelectFile(pdfPath) = False Then
            MsgBox("请选择pdf文件")
            Exit Sub
        End If
        Dim expPdfPath = Path.Combine(Path.GetDirectoryName(pdfPath), Path.GetFileNameWithoutExtension(pdfPath) & "_EXP_" & Format(Now, "yyyy-MM-dd HH_mm_ss") & ".pdf")
        ' 加载 PDF 文件
        Dim inputDocument As PdfDocument = PdfReader.Open(pdfPath, PdfDocumentOpenMode.Modify)
        Dim image As XImage '= XImage.FromFile(imagePath)

        ' 获取当前活动工作表
        Dim sheet As Worksheet = Globals.ThisWorkbook.Sheets("插入PDF")
        Dim imageList As Object(,)
        '
        With sheet
            ' 获取最后一行
            Dim lastRow As Integer = .Cells(.Rows.Count, 1).End(XlDirection.xlUp).Row

            ' 获取最后一列
            Dim lastColumn As Integer = .Cells(1, .Columns.Count).End(XlDirection.xlToLeft).Column

            ' 读取参数
            If lastRow = 1 Then
                MsgBox("没有可插入图片")
                Exit Sub
            Else
                imageList = .Cells(1, 1).resize(lastRow, 3).value
            End If
            '
            .Columns(4).clearcontents
            .Cells(1, 4).value = "结果"
        End With
        ' 初始化表格行号（从第2行开始，第1行为表头）
        Dim rowIndex As Integer
        Dim pageIndex As Integer
        Dim bz$
        For rowIndex = 2 To UBound(imageList)
            pageIndex = imageList(rowIndex, 3) - 1
            imagePath = imageList(rowIndex, 1)
            If pageIndex > inputDocument.Pages.Count - 1 Then
                bz = "页码超出pdf页数"
            ElseIf Dir(imagePath) = "" Then
                bz = "图片不存在"
            ElseIf Path.GetExtension(imagePath).ToUpper <> ".PNG" And Path.GetExtension(imagePath).ToUpper <> ".JPG" Then
                bz = $"格式不支持:{Path.GetExtension(imagePath).ToUpper}"
            Else
                Dim page As PdfPage = inputDocument.Pages(pageIndex)
                Dim width As Double = CDbl(sheet.Range("g1").Value) '图片宽度
                Dim height As Double = CDbl(sheet.Range("g2").Value) ' 右边距
                image = XImage.FromFile(imagePath)
                Dim rightMargin As Double = CDbl(sheet.Range("g3").Value) ' 右边距
                Dim bottomMargin As Double = CDbl(sheet.Range("g4").Value) '下边距
                ' 在页面上插入图片（根据右下角坐标定位）
                Using gfx As XGraphics = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append)
                    ' 图片的宽度和高度
                    'Dim width As Double = 100 ' 图片宽度
                    'Dim height As Double = image.PixelHeight * (width / image.PixelWidth) ' 按比例计算高度

                    ' 右下角坐标（假设为页面右下角，距离右边和下边各20点）


                    ' 计算图片的起始坐标（xPosition, yPosition）
                    Dim xPosition As Double = page.Width.Point - width - rightMargin ' 水平位置
                    Dim yPosition As Double = page.Height.Point - height - bottomMargin ' 垂直位置

                    ' 绘制图片
                    gfx.DrawImage(image, xPosition, yPosition, width, height)
                End Using
                bz = "成功"
            End If
            '
            sheet.Cells(rowIndex, 4).value = bz
        Next
        ' 保存修改后的 PDF
        inputDocument.Save(expPdfPath)
        inputDocument.Dispose()

        ' 提示完成
        MsgBox("图片插入完成！")
    End Sub
    Public Function SelectFile(ByRef fPath As String) As Boolean
        ' 创建 OpenFileDialog 实例
        Dim openFileDialog As New OpenFileDialog()

        ' 设置对话框属性
        openFileDialog.Title = "选择文件"
        openFileDialog.Filter = "PDF 文件 (*.pdf)|*.pdf" 'PDF 文件 (*.pdf)|*.pdf|图片文件 (*.png;*.jpg)|*.png;*.jpg|所有文件 (*.*)|*.*
        openFileDialog.FilterIndex = 1 ' 默认选择第一个过滤器
        openFileDialog.Multiselect = False ' 是否允许多选

        ' 显示对话框并检查用户是否点击了“确定”
        If openFileDialog.ShowDialog() = DialogResult.OK Then
            ' 获取用户选择的文件路径
            fPath = openFileDialog.FileName
            SelectFile = True

        Else
            SelectFile = False
        End If
    End Function
End Module
